package com.zx.map.controller;


import com.zx.map.service.AgentInfoService;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.OrdLogService;
import com.zx.map.service.domain.OrdLogDomain;
import com.zx.map.service.domain.ReportOrdLogDomain;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.OrdLogModel;
import com.zx.map.utils.SUConstants;
import com.zx.platform.context.DirectoryInfoContext;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;
import com.zx.platform.utils.report.ReportUtil;
import com.zx.utils.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/manage/ordLog")
public class OrdLogController {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(OrdLogController.class);

	@Autowired
	private OrdLogService ordLogService;
	@Autowired
	private AgentInfoService agentInfoService;
	@Autowired
	private MerchantInfoService merchantInfoService;

	/**
	 * 代理商今日交易查询
	 * edit by wenjw 2015.5.14
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/agentHistoryOrderList")
	public String agentHistoryOrderList(OrdLogDomain domain, Model model,
	                                    HttpServletRequest request) {
		try {// 初始化信息
			queryOrderPage(domain, model, request);
			return "/jsp/map/ordLog/agentHistoryOrderList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 分页查询交易记录
	 *
	 * @param domain
	 * @param model
	 * @param request
	 */
	private void queryOrderPage(OrdLogDomain domain, Model model, HttpServletRequest request) {
		initQueryData(domain);
		//查找当前操作员对应的代理商
		AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
		//作为查询条件查询直属商户
		if(domain.getIsDirect()>0&&curAgentInfoModel!=null){
			domain.setParentAgentId(curAgentInfoModel.getAgentId());
		}
		Map map = ordLogService.getPageByDomain(curAgentInfoModel, domain);
		setResultModelData(domain, map, model);
	}

	/**
	 * 历史交易查询
	 * edit by wenjw 2015.5.14
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/historyOrderList")
	public String historyOrderList(OrdLogDomain domain, Model model,
	                               HttpServletRequest request) {
		try {// 初始化信息
			queryOrderPage(domain, model, request);
			return "/jsp/map/ordLog/historyOrderList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 历史交易下载
	 * edit by wenjw 2015.5.14
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/downloadHistoryOrderList")
	public String downloadHistoryOrderList(OrdLogDomain domain, Model model,
	                                       HttpServletRequest request, HttpServletResponse response) {
		return downloadOrderList(domain, model, request, response, "历史交易查询");
	}

	/**
	 * 下载交易记录
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @param response
	 * @param fileName
	 * @return
	 */
	private String downloadOrderList(OrdLogDomain domain, Model model,
	                                 HttpServletRequest request, HttpServletResponse response, String fileName) {
		try {
			//查找当前操作员，看期是否有对应的代理商
			initQueryData(domain);
			//查找当前操作员对应的代理商
			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
			List<OrdLogModel> ordLogList = ordLogService.getListByOrdLogDomain(curAgentInfoModel, domain);
			List<ReportOrdLogDomain> reportList = new ArrayList<ReportOrdLogDomain>();
			for (OrdLogModel o : ordLogList) {
				//交易状态  增加为空检查
				if (StringUtils.isNotBlank(o.getTransStatus())) {
					o.setTransStatus(DirectoryInfoContext.getCaptionByKeyAndValue("2130", o.getTransStatus()));
				}
				ReportOrdLogDomain temp = new ReportOrdLogDomain();
				BeanUtils.copyProperties(o, temp);
				//设置订单类型  商户名称 代理商名称
				MerchantInfoModel tempMer = merchantInfoService.getModelByKey(o.getMerchantId());
				AgentInfoModel tempAgent = agentInfoService.getAgentInfoModelBySysAccount(o.getAgentSysAccount());
				temp.setAgentName(tempAgent.getAgentName());
				temp.setMerName(tempMer.getMerchantName());
				String transType = o.getTransType();
				temp.setTransType(StrUtils.getTransTypeById(transType));
				reportList.add(temp);
			}
			Map<Integer, Object> formatAttr = new HashMap<Integer, Object>();
			formatAttr.put(1, ReportUtil.Date_cro);

			String[] header = new String[]{"创建时间", "交易流水号", "订单类型", "订单金额", "商户账号", "商户名称",
						"代理商账号", "代理商名称", "收款订单号", "交易状态", "备注"};
			String sts = ReportUtil.exportReport(header, reportList, null,
						fileName, formatAttr, null, response);
			String[] st = sts.split("#");
			ReportUtil.download(response, st[0], st[1]);

		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
		return null;
	}

	/**
	 * 代理商今日交易查询
	 * edit by wenjw 2015.5.14
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/agentTodayOrderList")
	public String agentTodayOrderList(OrdLogDomain domain, Model model,
	                                  HttpServletRequest request) {
		try {// 初始化信息
			queryOrderPage(domain, model, request);
			return "/jsp/map/ordLog/agentTodayOrderList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 设置返回数据
	 *
	 * @param domain
	 * @param map
	 * @param model
	 */
	private void setResultModelData(OrdLogDomain domain, Map map, Model model) {
		int pageSize = domain.getPageSize();
		int pageNum = domain.getPageNum();
		List menuModelList = (List) map.get("list");
		int recordCount = Integer.valueOf(map.get("count").toString());
		if (pageSize * pageNum > recordCount + pageSize - 1) {
			pageNum = 1;
		}
		double paymentAmt=0d;
		try {
			paymentAmt=(Double) map.get("paymentAmt");
		} catch (Exception e) {
			e.printStackTrace();
			paymentAmt=0d;
		}

		model.addAttribute("list", menuModelList);
		model.addAttribute("paymentAmt",new BigDecimal(paymentAmt).setScale(2,BigDecimal.ROUND_HALF_UP) );
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageCount",
				PmpUtils.getPageCount(recordCount, pageSize));
		model.addAttribute("recordCount", recordCount);
		model.addAttribute("model", domain);
	}


	/**
	 * 今日交易查询
	 * edit by wenjw 2015.5.14
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/todayOrderList")
	public String todayOrderList(OrdLogDomain domain, Model model,
	                             HttpServletRequest request) {
		try {// 初始化信息
			queryOrderPage(domain, model, request);
			return "/jsp/map/ordLog/todayOrderList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 下载今日查询
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/downloadTodayOrderList")
	public String downloadTodayOrderList(OrdLogDomain domain, Model model,
	                                     HttpServletRequest request, HttpServletResponse response) {
		return downloadOrderList(domain, model, request, response, "今日交易");
	}

	/**
	 * 进入列表页面
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/list")
	public String list(OrdLogDomain domain, Model model,
	                   HttpServletRequest request) {

		try {// 初始化信息
			 queryOrderPage(domain, model, request);
			return "/jsp/map/ordLog/ordLogList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 大额订单监控
	 * 2、	实时监控系统中交易金额大于标准金额交易流水（eg：5W）
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/riskQuery")
	public String riskQuery(OrdLogDomain domain, Model model,
	                        HttpServletRequest request) {

		try {// 初始化信息
			initQueryData(domain);
			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
			if (curAgentInfoModel!=null){
				curAgentInfoModel.setHasSelf(true);
			}
			Map map = ordLogService.getPageRisk(curAgentInfoModel, domain);
			setResultModelData(domain,map,model);
			return "/jsp/map/ordLog/riskQuery";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 表单提交日期绑定
	 * edit by wenjw 2015.6.2
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

	/**
	 * 初始化查询数据
	 *
	 * @param domain
	 */
	private void initQueryData(OrdLogDomain domain) {
		Integer pageNum = domain.getPageNum();
		Integer pageSize = domain.getPageSize();
		Integer pageCount = domain.getPageCount();
		if (null == pageNum) {
			pageNum = 1;
		}
		if (null == pageSize) {
			pageSize = SUConstants.PAGE_COUNT;
		}
		domain.setPageNum(pageNum);
		domain.setPageSize(pageSize);

		if (StringUtils.isBlank(domain.getBeginDate())) {
			domain.setBeginDate(PmpUtils.dateToString(new Date(), "yyyy-MM-dd"));
		}
		if (StringUtils.isBlank(domain.getEndDate())) {
			domain.setEndDate(PmpUtils.dateToString(new Date(),
					"yyyy-MM-dd"));
		}
	}

	/**
	 * 弹出的新增修改页面
	 *
	 * @param ordLogModel
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(OrdLogModel ordLogModel, Model model, HttpServletRequest request) {
		try {
			String orderId = ordLogModel.getOrdId();
			if (orderId != "add" && StrUtils.isNotEmpty(orderId)) {
				ordLogModel = ordLogService.getModelByKey(orderId);
			}
			model.addAttribute("model", ordLogModel);
			return "/jsp/platform/ordLog/ordLogEdit";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * @return
	 */
	@RequestMapping("/update")
	public
	@ResponseBody
	OrdLogModel update(OrdLogModel model) {
		try {
			ordLogService.update(model);
			model.setSuccess(true);
			model.setMsg("保存信息成功");
			log.debug("保存信息成功");
		} catch (Exception e) {
			model.setSuccess(false);
			model.setMsg("保存信息失败");
			log.error("保存信息失败" + e.getMessage(), e);
		}
		return model;
	}

	/**
	 * @return
	 */
	@RequestMapping("/delete")
	public
	@ResponseBody
	OrdLogModel delete(OrdLogModel model) {
		try {
			ordLogService.delete(model);
			model.setSuccess(true);
			model.setMsg("删除信息成功");
			log.debug("删除信息成功");
		} catch (Exception e) {
			model.setSuccess(false);
			model.setMsg("删除信息失败");
			log.error("删除信息失败" + e.getMessage(), e);
		}
		return model;
	}

	/**
	 * @return
	 */
	@RequestMapping("/add")
	public
	@ResponseBody
	OrdLogModel add(OrdLogModel model) {
		try {
			ordLogService.add(model);
			model.setSuccess(true);
			model.setMsg("新增信息成功");
			log.debug("新增信息成功");
		} catch (Exception e) {
			model.setSuccess(false);
			model.setMsg("新增信息失败");
			log.error("新增信息失败" + e.getMessage(), e);
		}
		return model;
	}

}
